package com.pond.auth.util.sms;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("ihuyiSmsSender")
public class IhuyiSmsSender implements SmsSender {

    @Value("${sms.ihuyi.account}")
    private String account;  // 从 Nacos 配置读取 APIID

    @Value("${sms.ihuyi.password}")
    private String password; // 从 Nacos 配置读取 APIKEY

    @Value("${sms.ihuyi.template:【达信通】您的验证码是：{code}。请不要把验证码泄露给其他人。}")
    private String template; // 短信模板，支持配置，默认使用报备的格式
    
    // 根据官方demo，使用默认的模板格式
    private String getTemplate() {
        // 官方demo的默认模板（无签名）
        return "您的验证码是：{code}。请不要把验证码泄露给其他人。";
    }

    private static final String URL = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

    public boolean sendCode(String phone, String code) {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(URL);

        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK");

        String content = getTemplate().replace("{code}", code);
        
        // 添加调试日志
        System.out.println("=== 短信调试信息 ===");
        System.out.println("URL: " + URL);
        System.out.println("验证码: " + code);
        System.out.println("最终内容: " + content);
        System.out.println("内容长度: " + content.length());
        System.out.println("==================");

        NameValuePair[] data = {
                new NameValuePair("account", account),
                new NameValuePair("password", password),
                new NameValuePair("mobile", phone),
                new NameValuePair("content", content),
        };

        method.setRequestBody(data);

        try {
            int statusCode = client.executeMethod(method);

            if (statusCode != 200) {
                System.err.println("HTTP请求失败，状态码：" + statusCode);
                return false;
            }

            String response = method.getResponseBodyAsString();
            System.out.println("短信接口返回：" + response);

            Document doc = DocumentHelper.parseText(response);
            Element root = doc.getRootElement();

            String codeResult = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            System.out.println("返回码：" + codeResult + ", 描述：" + msg + ", 短信ID：" + smsid);

            return "2".equals(codeResult);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            method.releaseConnection();
        }
    }
}
